
import { Component , createContext } from 'react';

const { Provider , Consumer } = createContext();

function CartItems(props) {

    function mapper( element ){
        return (
            <div className='cart-item' key={element.id}>
                <span>{element.name}</span>
                <span>{element.price}</span>
                <span onClick={props.remove} data-id={element.id}>删除</span>
            </div>
        )
    }

    return (
        <div className='cart'>
            <Consumer>
                { items => items.map( mapper ) }
            </Consumer>
        </div>
    );
}

function Total( props ) {
    let count = (prev,curr)=> {
        return prev + curr.price * curr.number ;
    }
    return (
        <span className='total'>
            <Consumer>
                { items => items.reduce( count , 0 ) }
            </Consumer>
        </span>
    );
}

function SettleAccount(props) {
    return (
        <div className='settle-account'>
            <Total />
            <button>结算</button>
            <button>清空</button>
        </div>
    );
}


export default class Cart extends Component {
    state = {
        items: [
            { id: 1234 , name: 'Huawei P50 Pocket' , price: 8988 , number: 5 },
            { id: 4321 , name: 'Redmi K50 Pro' , price: 2999 , number: 2 } ,
            { id: 2343 , name: '红魔7Pro 暗夜骑士' , price: 4799 , number: 1 },
            { id: 2565 , name: '中兴Axon 30 5G' , price: 2498 , number: 1 }
        ]
    }
    remove = evt => {
        let t = evt.target ;
        let id = t.dataset.id ;
        console.log( id , typeof id );
        let arr = this.state.items ;
        let index = arr.findIndex( e => e.id == id );
        if( index != -1 ) {
            arr.splice( index , 1 );
            this.setState({
                items: arr
            });
        }
    }
    render(){
        const { items } = this.state ;
        return (
            <div className='cart-wrapper'>
                <Provider value={items}>
                    <CartItems remove={this.remove} />
                    <SettleAccount />
                </Provider>
            </div>
        );
    }
}